import {
  CallHandler,
  ExecutionContext,
  HttpStatus,
  Injectable,
  NestInterceptor,
  Scope
} from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { map } from 'rxjs'

import { MESSAGES } from '@/constants'
import { IConfig, IRequest } from '@/interfaces'

/**
 * 响应拦截器
 */
@Injectable({
  scope: Scope.REQUEST
})
export class ResponseInterceptor implements NestInterceptor {
  constructor(private readonly configService: ConfigService) {}

  async intercept(context: ExecutionContext, next: CallHandler) {
    const request = context.switchToHttp().getRequest<IRequest>()
    const { apiPath } = this.configService.get<IConfig['app']>('app')
    const isApi = request.url.includes(apiPath)

    if (!isApi) {
      return next.handle()
    }

    return next.handle().pipe(
      map(data => ({
        timestamp: Date.now(),
        status: HttpStatus.OK,
        message: MESSAGES.REQUEST_OK,
        data
      }))
    )
  }
}
